﻿using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Configuration;

namespace Keede.Rabbitmq.HandleService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        private readonly ServiceInstaller serviceInstaller;
        private readonly ServiceProcessInstaller processInstaller;

        public ProjectInstaller()
        {
            InitializeComponent();
            var handleService = ConfigurationManager.GetSection("handleService") as HandleServiceConfig;
            if (handleService == null) throw new Exception("HandleService服务配置错误!");

            processInstaller = new ServiceProcessInstaller();
            serviceInstaller = new ServiceInstaller();

            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.StartType = ServiceStartMode.Automatic;


            serviceInstaller.ServiceName = handleService.Service.Name;
            serviceInstaller.DisplayName = handleService.Service.DisplayName;
            serviceInstaller.Description = handleService.Service.Description;

            //var servicesDependedOn = new List<string> { "tcpip" };
            //var servicesDependedOnConfig = ConfManager.GetAppsetting("BgTask_ServicesDependedOn");

            //if (!string.IsNullOrEmpty(servicesDependedOnConfig))
            //    servicesDependedOn.AddRange(servicesDependedOnConfig.Split(new char[] { ',', ';' }));

            //serviceInstaller.ServicesDependedOn = servicesDependedOn.ToArray();

            //var serviceStartAfterInstall = ConfManager.GetAppsetting("BgTask_ServiceStartAfterInstall");
            //if (!string.IsNullOrEmpty(serviceStartAfterInstall) && serviceStartAfterInstall.ToLower() == "true")
            //   this.AfterInstall += new InstallEventHandler(ProjectInstaller_AfterInstall);

            Installers.Add(serviceInstaller);
            Installers.Add(processInstaller);
        }

        private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            var sc = new ServiceController(serviceInstaller.ServiceName);
            sc.Start();
        }
    }
}
